<?php
namespace app\api\controller\orderreceipt;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\common\model\buss\Buss;
use app\common\model\orderdata\StorageArea;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\Receipt;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\power\Rolepower;
use app\common\model\quotation\QuotationList;
use app\common\model\transit\Transport;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;

class Orderreceipt extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(202001);
    }
    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data         = input('get.');
        $data['Type'] = 'ware';
        $data         = init_where($data);
        $list         = ReceiptList::usergetlist($data, 'ware');
        foreach ($list['list'] as $key => $value) {
            if(empty($value['bussinfo']['UserName'])){
                if(!empty($value['tranuserinfo']['Name'])){
                    $list['list'][$key]['Name'] = $value['tranuserinfo']['Name'];
                }else{
                    if(!empty($value['bussuserinfo']['Name'])){
                        $list['list'][$key]['Name'] = $value['bussuserinfo']['Name'];
                    }else{
                        $list['list'][$key]['Name'] = '暂未完善名称';
                    }
                }
            }else{
                $list['list'][$key]['Name'] = $value['bussinfo']['UserName'];
            }
        }
        $list['tr']['title'] = ['收集员', '登记时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'WarehouseTime', 'State', 'ReceiptListId'];
        return myok($list);
    }
    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getreinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        //入库表单做一个汇总的功能
        //实际操作由产废信息生成入库的
        //在货物入库前可修改订单，一旦用户确认入库后将无法修改。
        $data                = ReceiptList::getinfo($id);
        $data                = $data['msg'];
        $data['list']        = HawaList::getgoodinfo($id, HawaList::STATETRANSPORT, 'retransport');
        $data['storagearea'] = StorageArea::getlist();
        // $data['buss'] =Transport::get($data['TranSportId']);
        $data['CELLPHONE'] = CELLPHONE;
        return myok($data);
    }

    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        //入库表就
        $data = ReceiptList::getinfo($id);
        // $data = HawaList::getgoodinfo($id, HawaList::STATETRANSPORT, 'transport');

        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data              = $data['msg'];
        $data['CELLPHONE'] = CELLPHONE;
        return myok($data);
    }
    public function getuserlist()
    {
        $ids  = input('ids');
        $ids  = explode(',', $ids);
        $data = UserModel::getpubliclist($ids);
        return myok($data);
    }

    public function createtransport()
    {
        $data = input('post.');
        if(!empty($data['orderGoodName'])){
            $data['orderGoodName'] = json_array($data['orderGoodName'],true);
        }else{
            $data['orderGoodName'] =[]; 
        }
        $file = ['sumgoodidlist', 'sumlistweight', 'orderReceiveWeight', 'orderid', 'ordergoodidlist', 'orderlistid', 'orderbussid', 'ordertranid', 'orderIsDifference', 'orderReceiveComments', 'orderUsage', 'orderStorageAreaId'];
        foreach ($file as $key => $value) {
            $data[$value] = explode(',', $data[$value]);
            if ($key > 2 && count($data[$file[2]]) !== count($data[$value])) {
                return myerr('参数不一致，请重新尝试');
            }
        }
        if (count($data[$file[2]]) !== count($data['orderGoodName'])) {
            return myerr('参数不一致，请重新尝试');
        }
        
        if (count($data['sumgoodidlist']) !== count($data['sumlistweight'])) {
            return myerr('参数不一致，请重新尝试');
        }
        // 检测订单状态是否为运输中
        $sbhawalist = HawaList::where('HawaListId', 'in', $data['orderlistid'])->select();
        foreach ($sbhawalist as $key => $value) {
            if ($value['State'] !== HawaList::STATETRANSPORT ) {
                return myerr('存在已入库的订单，请重新获取数据');
            }
            // 检测订单是否已经绑定入库id
            if (!empty($value['ReceiptListId'])) {
                return myerr('存在绑定的入库的订单，请联系收集员处理待确认订单');
            }
        }

        // 检测司机信息
        $tsid = Transport::get($data['bussid']);
        if (empty($tsid)) {
            return myerr('没有找到相应运输工具');
        }
        $tcid = $tsid->TransitCompanyId; //运输企业id
        // 根据业务员与收集员拆分订单
        // 当收集员与业务员一致的订单为一类
        // 单独收集员一类  单独业务员一类
        $ordercount  = 0; //收集单总个数
        $ordersbid   = []; //临时表id 根据此判断这条数据是第几个收集单的
        $idsb        = [];
        $adduserlist = []; //存储不同的 业务id 与收集员id
        foreach ($data['orderbussid'] as $key => $value) {
            $idsb[] = 'bid' . $value . 'tid' . $data['ordertranid'][$key];
        }
        foreach ($idsb as $key => $value) {
            //判断是否已经被同化
            if ($idsb[$key] == '-1') {
                continue;
            } else {
                $ordercount++;
                $ordersbid[$key]          = $ordercount;
                $adduserlist[$ordercount] = ['bussid' => $data['orderbussid'][$key], 'tuid' => $data['ordertranid'][$key]];

            }
            //判断剩下的是否与自身一致
            for ($i = $key + 1; $i < count($idsb); $i++) {
                //判断是否与当前的一致
                if ($value == $idsb[$i]) {
                    //如果一致 记录并且同化
                    $ordersbid[$i] = $ordercount;
                    $idsb[$i]      = '-1'; //-1代表被同化
                }
            }
        }
        //根据ordersbid 的标识增加出库表
        for ($i = 1; $i <= $ordercount; $i++) {
            $ndata = ['goodlist' => [], 'valuelist' => []];

            $sbindex = 0;
            foreach ($ordersbid as $key => $value) {
                if ($value == $i) {
                    // 获取报价信息 需要goodlist valuelist
                    $ndata['goodlist'][]  = $data['ordergoodidlist'][$key];
                    $ndata['valuelist'][] = $data['orderReceiveWeight'][$key];
                    $ndata['orderGoodName'][] = $data['orderGoodName'][$key];
                    $ndata['orderid'][]       = $data['orderid'][$key];
                }
            }
            //创建报价
            $quot = QuotationList::get_create_question($ndata);
            if (!$quot['code']) {
                return myerr($quot['msg']);
            }
            $ndata['quot'] = $quot['msg'];
            // 创建收集订单
            // idata){
            $ndata['bussid']        = $adduserlist[$i]['bussid']; //业务
            $ndata['tuid']          = $adduserlist[$i]['tuid']; //收集
            $ndata['tcid']          = $tcid; //运输单位
            $ndata['tsid']          = $data['bussid']; //运输工具id
            $ndata['WarehouseNote'] = $data['WarehouseNote'];
            $receiptlist = ReceiptList::screate($ndata);

            if (!$receiptlist['code']) {
                return myerr($receiptlist['msg']);
            }
            $receiptlist = $receiptlist['msg'];
            $upsblistid  = [];
            $uporder     = [];
            foreach ($ordersbid as $key => $value) {
                if ($value == $i) {
                    // 将收集订单与入库订单关联
                    $upsblistid[] = $data['orderlistid'][$key];
                    // 将收集子订单信息更新
                    $uporder[] = [
                        'HawaId'          => $data['orderid'][$key],
                        'ReceiveWeight'   => $data['orderReceiveWeight'][$key],
                        'StorageAreaId'   => $data['orderStorageAreaId'][$key],
                        'IsDifference'    => $data['orderIsDifference'][$key],
                        'ReceiveComments' => $data['orderReceiveComments'][$key],
                        'Usage'           => $data['orderUsage'][$key],
                    ];
                }
            }
            //更新订单表
            HawaList::where('HawaListId', 'in', $upsblistid)->update(['ReceiptListId' =>$receiptlist['ReceiptListId'],'TransitEndTime'=>date('Y-m-d H:i',time())]);
            //更新子表库存位置 $ReceiptList->ReceiptListId
            $user = new Hawa;
            $user->saveAll($uporder);
            // 通知相应负责人
            Sendmessage::Orderreceipt(1, $receiptlist['ReceiptListId']);
        }

        return myok($ordercount);
    }

    /**
     * 确认子订单数量
     * 业务员确定，判定数据是否调整过。
     * 调整过的话要求用户二次确认。
     * @return [type] [description]
     */
    public function reordertransport()
    {
        $data = input('post.');
        if(!empty($data['orderGoodName'])){
            $data['orderGoodName'] = json_array($data['orderGoodName'],true);
        }else{
            $data['orderGoodName'] =[]; 
        }
        $file = ['sumgoodidlist', 'sumlistweight', 'orderReceiveWeight', 'orderid', 'ordergoodidlist', 'orderlistid', 'orderbussid', 'ordertranid', 'orderIsDifference', 'orderReceiveComments', 'orderUsage', 'orderStorageAreaId'];
        foreach ($file as $key => $value) {
            $data[$value] = explode(',', $data[$value]);
            if ($key > 2 && count($data[$file[2]]) !== count($data[$value])) {
                return myerr('参数不一致，请重新尝试');
            }
        }
        if (count($data[$file[2]]) !== count($data['orderGoodName'])) {
            return myerr('参数不一致，请重新尝试');
        }
        if (count($data['sumgoodidlist']) !== count($data['sumlistweight'])) {
            return myerr('参数不一致，请重新尝试');
        }
        // 检测订单状态是否为运输中
        $sbhawalist = HawaList::where('HawaListId', 'in', $data['orderlistid'])->select();
        foreach ($sbhawalist as $key => $value) {
            if ($value['State'] !== HawaList::STATETRANSPORT) {
                return myerr('存在已入库的订单，请重新获取数据');
            }
        }

        //检测订单是否为待确认状态
        $order      = ReceiptList::get($data['id']);
        if (empty($order) || $order->State !== ReceiptList::STATEWAIT) {
            return myerr('收集员/业务员已经确认无法修改订单');
            //需要如果状态为已确认则设置一个延迟更新，只要修改则把订单的库存全部删掉等待用户从新确认添加进去。
        }

        // 检测司机信息
        $tsid = Transport::get($data['bussid']);
        if (empty($tsid)) {
            return myerr('没有找到相应运输工具');
        }
        $tcid = $tsid->TransitCompanyId; //运输企业id
        //修改产废表信息
        $uporder = [];
        foreach ($data['orderid'] as $key => $value) {
            // 将收集子订单信息更新
            $uporder[] = [
                'HawaId'          => $data['orderid'][$key],
                'ReceiveWeight'   => $data['orderReceiveWeight'][$key],
                'StorageAreaId'   => $data['orderStorageAreaId'][$key],
                'IsDifference'    => $data['orderIsDifference'][$key],
                'ReceiveComments' => $data['orderReceiveComments'][$key],
                'Usage'           => $data['orderUsage'][$key],
            ];
        }
        //更新子表库存位置 $ReceiptList->ReceiptListId
        $user = new Hawa;
        $user->saveAll($uporder);

        //修改入库信息
        $order      = ReceiptList::get($data['id']);
        $mustupdate = false;
        if (empty($order) || $order->State == ReceiptList::STATEDELETE) {
            return myerr('没有找到您需要的订单');
        }
        // 判断产品是否有修改
        $list    = Receipt::where('ReceiptListId', $data['id'])->select();
        $dellist = [];
        $addlist = [];
        $updlist = [];
        $upindex = 0;
        $upprice = 0; //需要增加的费用
        //判断数据是否有更新的和需要添加的
        foreach ($data['ordergoodidlist'] as $key => $value) {
            $addsb = false; //烧饼为false代表没有找到对应数据
            foreach ($list as $listkey => $listvalue) {
                if ($data['orderid'][$key] == $listvalue['HawaId']) {
                    //判断是否需要新增数据
                    $addsb = true; //找到此数据
                    //判断是否需要更新数据
                    if ((float) $data['orderReceiveWeight'][$key] !== $listvalue['Weight']) {
                        $updlist[$upindex]           = $listvalue;
                        $updlist[$upindex]['Weight'] = $data['orderReceiveWeight'][$key];
                        $upprice                     = $upprice + $listvalue['Price'] * ($data['orderReceiveWeight'][$key] - $listvalue['Weight']);
                        $upindex++;
                    }
                    break;
                }
            }
            if ($addsb == false) {
                $addlist['valuelist'][] = $data['orderReceiveWeight'][$key];
                $addlist['goodlist'][]  = $value; //新增数据
                $addlist['GoodName'][]  = $data['orderGoodName'][$key]; //新增数据
                $addlist['orderid'][]   = $data['orderid'][$key]; //新增数据
            }
        }

        //判断数据是否有删除的数据
        foreach ($list as $listkey => $listvalue) {
            $delsb = true;
            foreach ($data['ordergoodidlist'] as $key => $value) {
                if ($data['orderid'][$key] == $listvalue['HawaId']) {
                    $delsb = false; //找到此数据
                    break;
                }
            }
            if ($delsb == true) {
                $dellist[] = $listvalue['ReceiptId']; //删除
                $upprice   = $upprice - $listvalue['Price'] * $listvalue['Weight'];
            }
        }
        //修改子表
        //判断是否有需要删除的
        if (!empty($dellist)) {
            Receipt::destroy($dellist);
            $mustupdate = true;
        }
        //判断是否需要更新的数据
        if (!empty($updlist)) {
            foreach ($updlist as $key => $value) {
                $value->save();
            }
            $mustupdate = true;
        }
        //新增数据
        if (!empty($addlist)) {
            $mustupdate = true;
            $addquot    = QuotationList::get_create_question($addlist, $order['QuotationListId']);
            $hawa       = Receipt::screate($data['id'], $addlist['goodlist'], $addlist['valuelist'], $addquot['msg']['pricelist'], $addlist['GoodName'],$addlist['orderid']);
        }

        //修改主表金额
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            $quodata = QuotationList::get_create_question(
                ['goodlist' => $data['ordergoodidlist'],
                    'valuelist' => $data['orderReceiveWeight'],
                ],
                $order['QuotationListId']
            );
            $ndata['TotalCost']     = $order->TotalCost - $order->QuotationCost + $quodata['msg']['QuotationCost'];
            $ndata['QuotationCost'] = $quodata['msg']['QuotationCost'];
        }

        //判断是否有更新，需要通知产废单位二次确认
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            $ndata['State'] = ReceiptList::STATEWAIT;
        } else {
            if ($data['WarehouseNote'] == $order->WarehouseNote) {
                return myok('修改成功');
            }
        }
        //修改主表其他信息
        $ndata['id']            = $data['id'];
        $ndata['WarehouseNote'] = $data['WarehouseNote'];
        ReceiptList::user_reinfo($ndata, true, !$mustupdate);
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            return myok('订单有变更，请提示用户确认变更');
        } else {
            return myok('备注修改成功');
        }
    }
    /**
     * 创建收集员订单
     * @return [type] [description]
     */
    public function createorder()
    {
        $data = input('post.');
        //获取产品订单信息
        $data['goodlist']  = explode(',', $data['goodlist']);
        $data['valuelist'] = explode(',', $data['valuelist']);
        //删去为空的产品
        foreach ($data['valuelist'] as $key => $value) {
            if (empty($value)) {
                unset($data['goodlist'][$key]);
                unset($data['valuelist'][$key]);
            }
        }
        //获取报价信息
        $quot = QuotationList::get_create_question($data);
        if (!$quot['code']) {
            return myerr($quot['msg']);
        }
        $data['quot'] = $quot['msg'];
        //创建终端订单
        $hawa = ReceiptList::screate($data);
        if (!$hawa['code']) {
            return myerr($hawa['msg']);
        }
        $sb = Sendmessage::Orderreceipt(1, $hawa['msg']['ReceiptListId'], $hawa['msg']);
        if (!$sb['code']) {
            return myok('下单成功，请指导收集员现场确认');
        }
        return myok('下单成功，请指导收集员现场确认');
    }
    /**
     * 获取收集员列表
     * @return [type] [description]
     */
    public function getbusslist()
    {
        $data = Buss::getoklist();
        return myok($data);
    }
    /**
     * 获取运输工具列表
     * @return [type] [description]
     */
    public function gettransportlist()
    {
        $idarr               = HawaList::where('State', HawaList::STATETRANSPORT)->column('TranSportId');
        $sdata['where'][]    = ['TranSportId', 'in', $idarr];
        $data                = Transport::usergetlist($sdata, 'ware', false);
        $data['storagearea'] = StorageArea::getlist();
        return myok($data);
    }
    /**
     * 获取运输工具目前所承载的货物
     * @return [type] [description]
     */
    public function getsportordersum()
    {
        $id   = input('id');
        $data = HawaList::getgoodinfo($id, HawaList::STATETRANSPORT, 'transport');
        return myok($data);
    }
    /**
     * 获取收集员汇总订单
     * @return [type] [description]
     */
    public function getbussordersum()
    {
        $id   = input('id');
        $data = HawaList::getgoodinfo($id, HawaList::STATETRANSPORT);
        return myok($data);
    }
    /**
     * 确认子订单数量
     * 业务员确定，判定数据是否调整过。
     * 调整过的话要求用户二次确认。
     * @return [type] [description]
     */
    public function reorder()
    {
        $data           = input('post.');
        $data['goodid'] = explode(',', $data['goodlist']);
        $data['weight'] = explode(',', $data['valuelist']);
        $order          = ReceiptList::get($data['id']);
        $mustupdate     = false;
        if (empty($order) || $order->State == ReceiptList::STATEDELETE) {
            return myerr('没有找到您需要的订单');
        }

        // 判断产品是否有修改
        $list    = Receipt::where('ReceiptListId', $data['id'])->select();
        $dellist = [];
        $addlist = [];
        $updlist = [];
        $upindex = 0;
        $upprice = 0; //需要增加的费用
        //判断数据是否有更新的和需要添加的
        foreach ($data['goodid'] as $key => $value) {
            $addsb = false; //烧饼为false代表没有找到对应数据
            foreach ($list as $listkey => $listvalue) {
                if ($value == $listvalue['GoodId']) {
                    //判断是否需要新增数据
                    $addsb = true; //找到此数据
                    //判断是否需要更新数据

                    if ((float) $data['weight'][$key] !== $listvalue['Weight']) {
                        $updlist[$upindex]           = $listvalue;
                        $updlist[$upindex]['Weight'] = $data['weight'][$key];
                        $upprice                     = $upprice + $listvalue['Price'] * ($data['weight'][$key] - $listvalue['Weight']);
                        $upindex++;
                    }
                    break;
                }
            }
            if ($addsb == false) {
                $addlist['valuelist'][] = $data['weight'][$key];
                $addlist['goodlist'][]  = $value; //新增数据
            }
        }

        //判断数据是否有删除的数据
        foreach ($list as $listkey => $listvalue) {
            $delsb = true;
            foreach ($data['goodid'] as $key => $value) {
                if ($value == $listvalue['GoodId']) {
                    $delsb = false; //找到此数据
                    break;
                }
            }
            if ($delsb == true) {
                $dellist[] = $listvalue['HawaId']; //删除
                $upprice   = $upprice - $listvalue['Price'] * $listvalue['Weight'];
            }
        }
        //修改子表
        //判断是否有需要删除的
        if (!empty($dellist)) {
            Receipt::destroy($dellist);
            $mustupdate = true;
        }
        //判断是否需要更新的数据
        if (!empty($updlist)) {
            foreach ($updlist as $key => $value) {
                $value->save();
            }
            $mustupdate = true;
        }
        //新增数据
        if (!empty($addlist)) {
            $mustupdate = true;
            $addquot    = QuotationList::get_create_question($addlist, $order['QuotationListId']);
            $hawa       = Receipt::screate($data['id'], $addlist['goodlist'], $addlist['valuelist'], $addquot['msg']['pricelist']);
        }

        //修改主表金额
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            $quodata = QuotationList::get_create_question(
                ['goodlist' => $data['goodid'],
                    'valuelist' => $data['weight'],
                ],
                $order['QuotationListId']
            );
            $ndata['TotalCost']     = $order->TotalCost - $order->QuotationCost + $quodata['msg']['QuotationCost'];
            $ndata['QuotationCost'] = $quodata['msg']['QuotationCost'];
        }

        //判断是否有更新，需要通知产废单位二次确认
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            $ndata['State'] = ReceiptList::STATEWAIT;
        } else {
            if ($data['WarehouseNote'] == $order->WarehouseNote) {
                return myerr('订单数据无需修改');
            }
        }
        //修改主表其他信息
        $ndata['id']            = $data['id'];
        $ndata['WarehouseNote'] = $data['WarehouseNote'];
        ReceiptList::user_reinfo($ndata, true, !$mustupdate);
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
            return myok('订单有变更，请提示用户确认变更');
        } else {
            return myok('备注修改成功');
        }
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\orderreceipt\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/orderreceipt/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
